package com.hrbu.mp.generator.interceptor;

import com.alibaba.druid.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Description:
 * @Author: tanyajun
 * @CreateTime: 2021/3/18
 * @Blog: https://tanyajun.top
 */
public class MyInterceptor implements HandlerInterceptor {
    private List<String> exceptUrls;

    public List<String> getExceptUrls() {
        return exceptUrls;
    }

    public void setExceptUrls(List<String> exceptUrls) {
        this.exceptUrls = exceptUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请的url
        String url = request.getRequestURI();
        String requestUri = "";
        if (url.startsWith(request.getContextPath())) {
            requestUri = url.substring(request.getContextPath().length(), url.length());
        }
        //系统根目录
        if (StringUtils.equals("/", requestUri)) {
            return true;
        }
        //放行exceptUrls中配置的url
        for (String exurl : exceptUrls) {
            if (exurl.endsWith("/**")) {
                if (requestUri.startsWith(exurl.substring(0, url.length() - 3))) {
                    return true;
                }
            } else if (requestUri.startsWith(exurl)) {
                return true;
            }
        }
        if (url.indexOf("login") > 0) {
            return true;
        }

        // 获取session
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("USER_NAME");
        if (name != null) {
            return true;
        }
        request.setAttribute("msg", "您还没有登录，请先登录!");
        request.getRequestDispatcher("/login").forward(request, response);
        return false;
    }
}
